package mq

import (
	"context"
	"github.com/apache/rocketmq-client-go/v2"
	"github.com/apache/rocketmq-client-go/v2/consumer"
	"github.com/apache/rocketmq-client-go/v2/primitive"
	"github.com/zeromicro/go-zero/core/logx"
)

// InitUniversalConsumer InitUniversalConsumer 消费 ROCKETMQ_GO_LOG_LEVEL 设置为error 不打印ping日志
func InitUniversalConsumer(topic string) {
	var groupName = "user-api-group"
	namesrvs := []string{"124.220.82.36:9876"}
	// 设置消息轨迹
	traceCfg := &primitive.TraceConfig{
		Access:   primitive.Local,
		Resolver: primitive.NewPassthroughResolver(namesrvs),
	}
	c, _ := rocketmq.NewPushConsumer(
		consumer.WithGroupName(groupName),
		consumer.WithConsumerModel(consumer.Clustering),
		consumer.WithNsResolver(primitive.NewPassthroughResolver(namesrvs)),
		consumer.WithTrace(traceCfg),
	)
	// 设置Tag consumer.MessageSelector{Type: consumer.TAG, Expression: "user-api"}
	err := c.Subscribe(topic, consumer.MessageSelector{Type: consumer.TAG, Expression: "user-api"}, func(ctx context.Context,
		msgs ...*primitive.MessageExt) (consumer.ConsumeResult, error) {
		for i := range msgs {
			messageExt := msgs[i]
			logx.Infof("subscribe callback: topic:%s ,messageId:%s msg:%s\n", messageExt.Topic, messageExt.MsgId, string(messageExt.Body))
		}
		// 调用自己的业务
		return consumer.ConsumeSuccess, nil
	})
	if err != nil {
		logx.Errorf(err.Error())
	}
	// Note: start after subscribe
	err = c.Start()
	if err != nil {
		logx.Errorf(err.Error())
	}

}
